/**
 * 主要函数功能为完善客户端无法操作完成的复杂逻辑处理和相关缺失功能补充
 * 该文件为Parse服务器云函数功能文件
 * 作者:Jun Xiao
 * 于: 2016年6月1日
 */

var FunctionAssert = require('./functions_assert');
var Async = require('async');
var co = require('co');
var assert = require('./../routes/assert');
//请求验证码发送接口发送验证码并存储验证码信息
/**
 * 请求参数:
 * mobile 用户手机号
 * send_type 发送验证码的类型
 *
 */
Parse.Cloud.define('sendSMS', function (req, res) {
    var SMS_HOST_PRODUCTION = 'https://app.cloopen.com:8883';
    var SMS_HOST_SANDBOX = 'https://sandboxapp.cloopen.com:8883';
    var accountSid = '8a48b5515099b1880150a32360ec1ab7';
    var accountToken = 'c9ddcbfc0171400a927a6baee5f7389d';
    var appId = '8a48b5515099b1880150a32642781ad3';
    //避免过大的开销,这里需要先检查电话号码的合理性
    if (!req.params.mobile) {
        res.error("获取手机号码失败");
    }
    if (!req.params.send_type) {
        res.error("获取发送类型失败");
    }
    var msg_type_code = {
        'sign': 45930,
        'change_mobile': 45940,
        'change_password': 45937,
        "couponGet": 102717,
        "mobileAutoSign": 102720,
        "mobileLogin": 104070,
        "kd_changepass":137428,
        "kd_sign":137426,
        "kd_mobileLogin":137828
    };
    var templateId = msg_type_code[req.params.send_type];
    var moment = require('moment');
    var timeStr = moment().format('YYYYMMDDHHmmss');
    var crypto = require('crypto');
    var SigParameter_obj = crypto.createHash('md5').update(accountSid + accountToken + timeStr);
    var SigParameter = SigParameter_obj.digest('hex').toUpperCase();
    var Path = '/2013-12-26/Accounts/' + accountSid + '/SMS/TemplateSMS?sig=' + SigParameter;
    var urlInfo = {
        host: SMS_HOST_PRODUCTION,
        path: Path
    };
    var headers = {
        "Authorization": new Buffer(accountSid + ':' + timeStr).toString('base64')
    };
    ////生成随机的code,写入到redis
    var data = {
        to: req.params.mobile,
        appId: appId,
        templateId: templateId
    };
    switch (templateId) {
        case 45930:
        case 45940:
        case 45937:
        case 104070:
        case 137428:
        case 137426:
            FunctionAssert.setCode(req.params.mobile, templateId, function (error, code) {
                var data = {
                    to: req.params.mobile,
                    appId: appId,
                    templateId: templateId,
                    datas: [code, '5']
                };
                if(!error){
                    FunctionAssert.HTTPRequests(urlInfo, data, 'POST', headers, function (err, result) {
                        if (!err) {
                            res.success("发送成功");
                        } else {
                            res.error(result.message);
                        }
                    });
                }else{
                    var MessageCode = new Parse.Object.extend('PYMessageCode');
                    var message_code = new MessageCode();
                    message_code.set("code", code);
                    message_code.set("send_type", req.params.send_type);
                    message_code.set("mobile", req.params.mobile);
                    message_code.set("expired_data", new Date().getTime() + 1000 * 60 * 5);
                    message_code.set("is_validate", false);
                    message_code.save().then(function(){
                        FunctionAssert.HTTPRequests(urlInfo, data, 'POST', headers, function (err, result) {
                            if (!err) {
                                res.success("发送成功");
                            } else {
                                res.error(result.message);
                            }
                        });
                    });
                }
            });
            break;
        case 102717:
            var couponWorth = req.params.couponWorth;
            if (!couponWorth) {
                res.error("未找到红包价格参数");
                return;
            }
            data.datas = [couponWorth];
            FunctionAssert.HTTPRequests(urlInfo, data, 'POST', headers, function (err, result) {
                if (!err) {
                    res.success("发送成功");
                } else {
                    res.error("发送短信失败");
                }
            });
            break;
        case 102720:
            var password = req.params.password;
            if (!password) {
                res.error("未找到自定义密码");
                return;
            }
            data.datas = [req.params.mobile, password];
            FunctionAssert.HTTPRequests(urlInfo, data, 'POST', headers, function (err, result) {
                if (!err) {
                    res.success("发送成功");
                } else {
                    res.error("发送短信失败");
                }
            });
            break;
        default :
            res.error("未知的短信发送模板");
    }
});


//验证验证码正确与否
/**
 * 请求参数:
 * sms_code  待验证的验证码
 * code_type 验证类别
 * mobile    手机号码
 */
Parse.Cloud.define('validateSMSCode', function (req, res) {
    var sms_code = req.params.sms_code;
    var code_type = req.params.code_type;
    var mobile = req.params.mobile;
    if (!sms_code || !code_type || !mobile) {
        res.error("必要参数不能为空");
    } else {
        //首先查询redis数据库,获取结果
        var code = FunctionAssert.getCode(mobile, code_type, function (err, db_code) {
            console.log(err,db_code);
            if (!err) {
                if (db_code) {
                    //表示在redis找到了数据,则直接对比code
                    if (sms_code == db_code) {
                        res.success("验证成功");
                    } else {
                        res.success("验证码错误");
                    }
                } else {
                    //表示已经过期
                    res.success("验证码已经过期");
                }
            } else {
                //获取mongodb的数据
                var query = new Parse.Query('PYMessageCode');
                query.equalTo("mobile", mobile);
                query.equalTo("send_type", code_type);
                query.equalTo("is_validate", false);
                query.find({
                    success: function (results) {
                        if (results.length > 0) {
                            message_code = results[0].get('code');
                            message_expired = results[0].get('expired_data');
                            if (message_expired < new Date().getTime()) {
                                //表示已经过期
                                res.error("验证码已经过期");
                            } else {
                                if (message_code == sms_code) {
                                    res.success("验证通过");
                                    //验证通过的需要将is_validate改变状态
                                    var MessageCode = new Parse.Object.extend('PYMessageCode');
                                    var message_code = new MessageCode();
                                    message_code.id = results[0].id;
                                    message_code.set("is_validate", true);
                                    message_code.save();
                                } else {
                                    res.error("验证码错误");
                                }
                            }
                        } else {
                            res.error("验证码信息错误");
                        }
                    },
                    error: function () {
                        res.error("验证码信息错误");
                    }
                });
            }
        });
    }
});

//这里是对老用户的密码进行更新,修改完之后删除在老用户表中的记录
/**
 * 请求参数
 * mobile  用户手机号
 * realPassword 用户输入的真实密码
 * user  请求用户的对象,请在请求头中加入session_token在实现该功能
 */
Parse.Cloud.define('ReDealOldUserPassChange', function (req, res) {
    var mobile = req.params.mobile;
    var real_pass = req.params.realPassword;
    //获取用户信息
    var userInfo = req.user;
    Parse.Cloud.useMasterKey();
    if (!mobile || !real_pass) {
        res.error("必要数据为空");
    } else {
        if (!userInfo) {
            res.error("获取用户信息失败");
        } else {
            userInfo.set('password', real_pass).save(null, {
                success: function (user) {
                    //修改成功后需要将原记录清除掉
                    var query = new Parse.Query('PYOldUsers');
                    query.equalTo('user_mobile', mobile);
                    query.find({
                        success: function (results) {
                            if (results.length > 0) {
                                //删除object
                                console.log(results);
                                results[0].destroy().then(function (res_del) {
                                    res.success("修改密码并删除原纪录成功");
                                }, function (err) {
                                    //此处我得需要修改掉这个记录的密码修改记录
                                    res.error("删除原纪录失败,修改密码成功")
                                });
                            } else {
                                res.error("未找到老用户信息")
                            }
                        }, error: function (error) {
                            res.error("查找失败");
                        }
                    });
                }, error: function (err) {
                    res.error("修改密码错误");
                }
            });
        }
    }
});

//根据用户的手机号码修改用户的密码
/**
 * 修改密码接口
 * 请求参数:
 * newPassword  需要被设置的新密码
 * mobile       用户手机号码
 */
Parse.Cloud.define('changeUserPassword', function (req, res) {
    var new_pass = req.params.newPassword;
    var mobile = req.params.mobile;
    var objectId = req.params.objectId;
    //获取用户信息
    Parse.Cloud.useMasterKey();
    if (!mobile && !objectId) {
        res.error("获取用户信息失败!")
    } else {
        if (objectId) {
            var queryObj = new Parse.Query('_User');
            queryObj.get(objectId, {
                success: function (user) {
                    if (user) {
                        user.set('password', new_pass).save(null, {
                            success: function (user) {
                                res.success("ID修改成功");
                            }, error: function (err) {
                                res.error("ID修改失败");
                            }
                        })
                    } else {
                        res.error("该用户不存在");
                    }
                },
                error: function (err) {
                    res.error("查找用户失败");
                }
            });
        } else {
            //修改密码前需要把旧用户信息直接删除
            var oldUser = new Parse.Query('PYOldUsers');
            oldUser.equalTo('user_mobile', mobile);
            oldUser.first().then(function (old) {
                if (old) {
                    old.destroy().then(function (resutls) {
                        console.log(resutls);
                    });
                }
                var query = new Parse.Query('_User');
                query.equalTo('mobile', mobile);
                query.find({
                    success: function (user) {
                        if (user.length) {
                            user[0].set('password', new_pass).save(null, {
                                success: function (user) {
                                    res.success("修改成功");
                                }, error: function (err) {
                                    res.error("修改失败");
                                }
                            })
                        } else {
                            res.error("该用户手机号不存在");
                        }
                    },
                    error: function (err) {
                        res.error("查找用户失败");
                    }
                });

            }, function (err, error) {
                var query = new Parse.Query('_User');
                query.equalTo('mobile', mobile);
                query.find({
                    success: function (user) {
                        if (user.length) {
                            user[0].set('password', new_pass).save(null, {
                                success: function (user) {
                                    res.success("修改成功");
                                }, error: function (err) {
                                    res.error("修改失败");
                                }
                            })
                        } else {
                            res.error("该用户手机号不存在");
                        }
                    },
                    error: function (err) {
                        res.error("查找用户失败");
                    }
                });
            });
        }
    }

});

//转移老用户的token信息到新数据库
/**
 * 工具函数,不为SDK所调用,只负责转移数据时使用
 * 请求参数:
 * token    原用户的Token秘钥
 * mobile   用户的手机号码
 */
Parse.Cloud.define('moveOldUserToken', function (req, res) {
    //将老用户写入到一张表中
    var token = req.params.token;
    var user_mobile = req.params.mobile;
    //需要先查找是否有该手机号的数据
    var _PYOldUsers = new Parse.Query("PYOldUsers");
    _PYOldUsers.equalTo('user_mobile', user_mobile);
    _PYOldUsers.first().then(function (pyoldUser) {
        if (pyoldUser) {
            res.success("数据已经存在不用插入");
        } else {
            //根据这个写入一张表中去
            var PYOldUsers = Parse.Object.extend('PYOldUsers');
            var oldUser = new PYOldUsers();
            oldUser.set("token", token);
            oldUser.set("user_mobile", user_mobile);
            oldUser.set("is_modified", false);
            oldUser.save(null, {
                success: function (oldUser) {
                    res.success();
                },
                error: function () {
                    res.error("插入失败");
                    console.log("插入失败", user_mobile);
                }
            });
        }
    }, function (er, error) {
        res.error("查询数据出错");
    })

});


//批量修改指针错误问题
/**
 * 工具函数,不为SDK所调用,只负责转移数据时使用
 * 请求参数:
 * className  需要操作的类名
 * mustKey    类中一直存在的字段名
 * modifiedKey需要更正的字段名
 * limit      查询的限制
 * skip       需要跳过的数量
 */
Parse.Cloud.define('refDate', function (req, res) {
    var className = req.params.className;
    var mustKey = req.params.mustKey;
    var modifiedKey = req.params.modifiedKey;
    var query = new Parse.Query(className);
    var limit = parseInt(req.params.limit);
    var skip = parseInt(req.params.skip);
    Parse.Cloud.useMasterKey();
    query.exists(mustKey);
    query.limit(limit);
    query.skip(skip);
    query.find({
        success: function (obj) {
            console.log(obj.length);
            for (var m = 0; m < obj.length; m++) {
                for (var j = 0; j < modifiedKey.length; j++) {
                    obj[m].set(modifiedKey[j], obj[m].get(modifiedKey[j]));
                }
                obj[m].set("hasChanged", true);
                obj[m].save(null, {
                    success: function (msg) {
                        console.log("成功")
                    }
                });
            }
            res.success("成功");
        },
        error: function (err) {
            console.log(err);
            res.error("是啊比");
        }
    });
});


//专用于修改药品分类的指针修改
//批量修改指针错误问题
/**
 * 工具函数,不为SDK所调用,只负责转移数据时使用
 * 请求参数:
 * className  需要操作的类名
 * mustKey    类中一直存在的字段名
 * modifiedKey需要更正的字段名
 * limit      查询的限制
 * skip       需要跳过的数量
 */
Parse.Cloud.define('refDateCate', function (req, res) {
    var className = req.params.className;
    var mustKey = req.params.mustKey;
    var modifiedKey = req.params.modifiedKey;
    var query = new Parse.Query(className);
    var limit = parseInt(req.params.limit);
    var skip = parseInt(req.params.skip);
    Parse.Cloud.useMasterKey();
    query.exists(mustKey);
    query.limit(limit);
    query.skip(skip);
    query.find({
        success: function (obj) {
            console.log(obj.length);
            for (var m = 0; m < obj.length; m++) {
                obj[m].set("category", obj[m].get("categories"));
                obj[m].save(null, {
                    success: function (msg) {
                        console.log("成功")
                    }
                });
            }
            res.success("成功");
        },
        error: function (err) {
            console.log(err);
            res.error("是啊比");
        }
    });
});


//检查指针错误函数
//批量修改指针错误问题
/**
 * 工具函数,不为SDK所调用,只负责转移数据时使用
 * 请求参数:
 * query      查询的ID
 * queryKey   所在的字段名 比如:bodypart
 * className  需要操作的类名
 * queryClass Pointer指向的类的名字
 */
Parse.Cloud.define('getArrayPointer', function (req, res) {
    var querystr = req.params.query;
    var queryKey = req.params.queryKey;
    var className = req.params.className;
    var queryClass = req.params.queryClass;
    var query = new Parse.Query(className);
    query.containedIn(queryKey, [Parse.Object.extend(queryClass).createWithoutData(querystr)]);
    query.find({
        success: function (msg) {
            res.success("查找到的数据数量为:" + msg.length);
        }, error: function (err) {
            console.log(err);
        }
    })
});


//评论添加用户积分钩子函数
/**
 * 评论完成后添加用户积分
 * 请求参数:
 * user   session_token请确保在请求头中
 * object 此为自动生成后传递的对象,即保存后的对象
 *
 * 该函数现在实现的积分增加功能有:
 * 1 实现基本加分,每次评论加10分
 * 2 10次评论加分,达到10次额外加分50
 * 3 100次评论加分,达到100次额外加200分
 */
Parse.Cloud.afterSave('PYDrugComment', function (req, res) {
    var commentAddPoints = {"normalComment": 10, "firstTenComments": 50, "firstHundredComments": 200};
    var commentUser = req.user;
    Parse.Cloud.useMasterKey();
    var object_saved = req.object;
    var locations = "PYDrug";
    var target = object_saved.get('drug').id;
    var oldNumbers = commentUser.get('point');
    if (req.original) {
        res.success("修改不操作");
    } else {
        //这里就是新增了,新增需要添加用户的积分
        //查询下用户的具体评论次数.若刚好为9次,添加2次积分,一次本次评论积分,一次10评论积分
        var query = new Parse.Query("PYPoints");
        query.equalTo('user', commentUser);
        query.count({
            success: function (count) {
                switch (count) {
                    case 9:
                        //同时添加2条积分记录到数据库
                        FunctionAssert.addUserPoints(commentUser, commentAddPoints.normalComment, locations, 'comment', target, oldNumbers, function (res) {
                            if (res) {
                                FunctionAssert.addUserPoints(commentUser, commentAddPoints.firstTenComments, locations, 'firstTenComment', target, oldNumbers + commentAddPoints.normalComment, function (res) {
                                    if (res) {
                                        console.log("成功,且达到了10次评论额外加分");
                                    } else {
                                        console.log("失败10");
                                    }
                                });
                            } else {
                                console.log("失败normal");
                            }
                        });
                        break;
                    case 99:
                        //同时添加2条积分记录到数据库
                        FunctionAssert.addUserPoints(commentUser, commentAddPoints.normalComment, locations, 'comment', target, oldNumbers, function (res) {
                            if (res) {
                                FunctionAssert.addUserPoints(commentUser, commentAddPoints.firstHundredComments, locations, 'firstHundredComment', target, oldNumbers + commentAddPoints.normalComment, function (res) {
                                    if (res) {
                                        console.log("成功,且达到了100次评论额外加分");
                                    } else {
                                        console.log("失败100");
                                    }
                                });
                            } else {
                                console.log("失败normal");
                            }
                        });
                        break;
                    default :
                        FunctionAssert.addUserPoints(commentUser, commentAddPoints.normalComment, locations, 'comment', target, oldNumbers, function (res) {
                            if (res) {
                                console.log("成功");
                            } else {
                                console.log(res);
                            }
                        });
                        break;
                }
            }
        });
    }
});

//转让药店功能函数
/**
 * 请求参数:
 * user     请确保请求头中包含正确的session_token
 * changeMobile 被转让人的手机号码
 * changeId     被转让人的用户ID 二者传其一即可,若同时传入,以ID为准
 * pharmacyId   店铺的ID
 *
 * 此功能函数发起者必须为该药店的负责人或者实际店长
 */
Parse.Cloud.define('exchangePharmacy', function (req, res) {
    var user = req.user;
    var changerMobile = req.params.changeMobile;
    var changerObjectId = req.params.changeId;
    var pharmacyId = req.params.pharmacyId;
    Parse.Cloud.useMasterKey();
    if (!changerMobile && !changerObjectId) {
        res.error("请提供被转让人的用户信息");
        return;
    }
    if (!pharmacyId) {
        res.error("请提供被转让药店ID");
        return;
    }
    //首先获取被转让人的信息
    //是否是id转让
    var changeUser = null;
    var userQuery = new Parse.Query('_User');
    if (changerObjectId) {
        userQuery.get(changerObjectId).then(function (changeUser) {
            //被转让人的身份
            var changerUserType = changeUser.get("userType");
            if (changerUserType == 'manager') {
                res.error("连锁管理经理不能被转让店铺");
                return;
            }
            //转让人的身份类别
            var userType = user.get("userType");
            var queryOwner = new Parse.Query("PYPharmacy");
            queryOwner.get(pharmacyId).then(function (pharmacyObj) {
                if (pharmacyObj.length == 0) {
                    res.error("获取转让药店信息失败");
                    return;
                } else {
                    if (pharmacyObj.get('owner').id == user.id || pharmacyObj.get("manager").id == user.id) {
                        Parse.Object.extend("PYPharmacy").createWithoutData(pharmacyId).set("owner", changeUser)
                            .save()
                            .then(function (ppp) {
                                //权限认证通过,开始转让店铺,这里要先查看是否只有一家药店
                                if (userType == 'director') {
                                    var queryCount = new Parse.Query("PYPharmacy");
                                    queryCount.equalTo("owner", user).count().then(function (count) {
                                        if (count == 0) {
                                            //表示变化自身的身份
                                            user.set("userType", "normal").save();
                                        }
                                    });
                                }
                                if (changerUserType == 'normal') {
                                    changeUser.set("userType", "director").save();
                                }
                                res.success("转让成功");
                            }, function (err) {
                                res.error("失败");
                            });
                    } else {
                        res.error("权限鉴定失败,请尝试重新登录账号");
                    }
                }
            }, function (err) {
                res.error("获取药店信息失败");
            })
        }, function (err) {
            res.error("获取用户失败");
        })
    }

    if (changerMobile) {
        userQuery.equalTo('username', changerMobile);
        userQuery.find({
            success: function (usr) {
                changeUser = usr[0];
                if (changeUser) {
                    var changerUserType = changeUser.get("userType");
                    var userType = user.get("userType");
                    //检查用户是否是这家店的店长或者管理者
                    var queryOwner = new Parse.Query("PYPharmacy");
                    queryOwner.get(pharmacyId, {
                        success: function (pharmacyObj) {
                            if (pharmacyObj.length == 0) {
                                res.error("获取转让药店信息失败");
                                return;
                            }
                            if (pharmacyObj.get('owner').id == user.id || pharmacyObj.get("manager").id == user.id) {
                                //权限认证通过,开始转让店铺,这里要先查看是否只有一家药店
                                Parse.Object.extend("PYPharmacy").createWithoutData(pharmacyId).set("owner", changeUser).save(null, {
                                    success: function (pharmacy) {
                                        if (userType == 'director') {
                                            var queryCount = new Parse.Query("PYPharmacy");
                                            queryCount.equalTo("owner", user);
                                            queryCount.count({
                                                success: function (count) {
                                                    if (count == 0) {
                                                        user.set("userType", "normal").save();
                                                    }
                                                }
                                            })
                                        }
                                        if (changerUserType == 'normal') {
                                            changeUser.set("userType", "director").save();
                                        }
                                        res.success("转让成功");
                                    }, error: function (err) {
                                        res.error("转让失败");
                                    }
                                });
                            } else {
                                res.error("权限鉴定失败,请尝试重新登录账号");
                            }
                        }, error: function (err) {
                            res.error(err);
                        }
                    })
                }
            }
        })
    }
});
/**
 * 请求参数:
 * user     请确保请求头中包含正确的session_token
 * content  活动描述
 * isTop    是否置顶
 * beginDate   活动开始时间,形式如:2016-06-01T10:35:23.855Z 或者精确到毫秒级的时间戳
 * name     活动名称
 * endDate  活动结束时间,形式如:2016-06-01T10:35:23.855Z 或者精确到毫秒级的时间戳
 * images   活动介绍图片
 * url      活动详情网址
 */

Parse.Cloud.define('managerPublicActivity', function (req, res) {
    var user = req.user;
    var content = req.params.content;
    var isTop = req.params.isTop;
    var beginDate = req.params.beginDate;
    var name = req.params.name;
    var endDate = req.params.endDate;
    var images = req.params.images;
    var url = req.params.url;
    var pharmacies = req.params.pharmacies;

    if (!user) {
        res.error("获取用户信息失败");
        return;
    }
    if (!name || !content) {
        res.error("活动名称和活动介绍不能为空");
        return;
    }
    if (!images && !url) {
        res.error("图片信息和网址信息至少一个不能为空");
        return;
    }
    //开始写入之前,检查用户身份并获取店铺列表
    var userType = user.get("userType");
    if (userType != 'manager') {
        res.error("用户身份不是负责人,无法一键创建活动");
        return
    }
    //如果传入的店铺Id数据不为空的话
    if (pharmacies) {
        //处理字符串拼接
        pharmacies_list = pharmacies.split("-");
        //验证药店是否是该用户的负责药店
        FunctionAssert.createPharmacyActivity(pharmacies_list, name, content, isTop, beginDate, endDate, url, images, true);
        res.success("活动正在后台成功");
        return;
    }
    console.log(123);
    //获取管理下的所有药店
    var queryPharmacy = new Parse.Query("PYPharmacy");
    queryPharmacy.equalTo("manager", user).find().then(
        function (pharmacies) {
            FunctionAssert.createPharmacyActivity(pharmacies, name, content, isTop, beginDate, endDate, url, images, false);
            res.success("活动正在后台成功");
        },
        function (err) {
            res.error("获取药店列表失败");
        }
    )
});


//领取优惠券之前检查优惠券数量是否能够被领取
/**
 * 检查优惠券数量
 * 请求参数:
 * user   session_token请确保在请求头中
 * object 此为自动生成后传递的对象,即保存后的对象
 *
 * 该函数现在实现的积分增加功能有:
 * 1 实现基本加分,每次评论加10分
 * 2 10次评论加分,达到10次额外加分50
 * 3 100次评论加分,达到100次额外加200分
 */
Parse.Cloud.beforeSave('PYCoupon', function (req, res) {

    var beforeObject = req.object;
    var pharmacyCouponT = beforeObject.get('couponTemplate');
    var pharmacyObj = beforeObject.get('fromPharmacy');
    Parse.Cloud.useMasterKey();
    //查询该药店该模板设定的领取数量
    var _couponT = new Parse.Query("PYCouponTemplate");
    _couponT.get(pharmacyCouponT.id, {
        success: function (_T) {
            var couponsLimit = _T.get('count');
            var isNoMore = _T.get('isNoMore');
            if (isNoMore) {
                res.error("该优惠券已领完");
                return;
            }
            //查询已经领取的数量
            var query = new Parse.Query('PYCoupon');
            query.equalTo('fromPharmacy', pharmacyObj);
            query.equalTo('couponTemplate', pharmacyCouponT);
            query.count().then(function (countLimit) {
                console.log(countLimit);
                if (countLimit < couponsLimit - 1) {
                    res.success("可以直接领取");
                    return;
                }
                if (countLimit == couponsLimit - 1) {
                    //此处需要修改模板的属性
                    pharmacyCouponT.set("isNoMore", true).save().then(function (pCoupon) {
                        res.success("最后一张领取成功");
                    }, function (err) {
                        res.error("修改属性失败")
                    })
                }
                if (countLimit > couponsLimit) {
                    res.error("该优惠券已领完");
                }
            }, function (err) {
                res.error("查询优惠券数量失败")
            })
        },
        error: function (err) {
            res.error("模板不存在");
        }
    });

});

/**
 *
 */
Parse.Cloud.define('incCircleFollowNumber', function (req, res) {

    var user = req.params.userId;
    var followType = req.params.followType;
    var circleId = req.params.circleId;

    if (!user) {
        res.error("获取用户信息失败");
        return;
    }
    if (!followType) {
        res.error("获取指定信息失败");
        return;
    }
    //获取用户对象
    var _User = new Parse.Query("_User");
    _User.get(user).then(function (userObj) {
        //查询该信息记录是否已经存在
        var PYUserNum = new Parse.Query("PYUserNum");
        PYUserNum.equalTo('user', userObj);
        PYUserNum.first().then(function (PYUserNumObj) {
            if (PYUserNumObj) {
                //表示存在该条数据,则修改该数据
                var oldNumber = PYUserNumObj.get('followerNum');
                if (oldNumber == 0 && parseInt(followType) == -1) {
                    res.error("关注数量已经为零,不能再取消关注");
                    return;
                }
                PYUserNumObj.increment('followerNum', parseInt(followType));
                PYUserNumObj.save().then(function (results) {
                    if (!circleId) {
                        res.success("修改关注人数成功");
                    } else {
                        //如果圈子ID不为空,则还需要将圈子的数据更新
                        var pyCircle = new Parse.Object.extend("PYTopicCircle").createWithoutData(circleId);
                        var PYCircleUserNum = new Parse.Query("PYCircleUserNum");
                        PYCircleUserNum.equalTo('user', userObj);
                        PYCircleUserNum.equalTo('circle', pyCircle);
                        PYCircleUserNum.first().then(function (pyCircleUserNumObj) {
                            if (pyCircleUserNumObj) {
                                var oldCircleNumber = pyCircleUserNumObj.get('followerNum');
                                if (oldCircleNumber == 0 && parseInt(followType) == -1) {
                                    res.error("圈子关注数量已经为零,不能再取消关注");
                                    return;
                                }
                                pyCircleUserNumObj.increment('followerNum', parseInt(followType));
                                pyCircleUserNumObj.save().then(function (results) {
                                    res.success("修改关注人数成功,圈子数据同步修改");
                                }, function (err, error) {
                                    res.error("修改圈子数据失败");
                                })
                            } else {
                                var _PYCircleUserNum = Parse.Object.extend("PYCircleUserNum");
                                var _pyCircleUserNum = new _PYCircleUserNum();
                                _pyCircleUserNum.set('feedNum', 0);
                                _pyCircleUserNum.set('followerNum', 1);
                                _pyCircleUserNum.set('user', userObj);
                                _pyCircleUserNum.set('circle', pyCircle);
                                _pyCircleUserNum.set('isRecommend', false);
                                _pyCircleUserNum.set('askNum', 0);
                                _pyCircleUserNum.set('countNum', 0);
                                _pyCircleUserNum.save().then(function (results) {
                                    res.success("修改关注人数成功,增加圈子数据成功")
                                }, function (err, error) {
                                    res.error("增加圈子数据失败")
                                })
                            }
                        })
                    }
                }, function (err, error) {
                    res.error("修改关注人数失败");
                })
            } else {
                //若没有找到数据,则要新添加数据
                if (parseInt(followType) == -1) {
                    res.error("无法给没有关注的人取消关注");
                    return;
                }
                var _PYUserNum = Parse.Object.extend("PYUserNum");
                var pyUserNum = new _PYUserNum();
                pyUserNum.set('feedNum', 0);
                pyUserNum.set('followerNum', 1);
                pyUserNum.set('user', userObj);
                pyUserNum.set('askNum', 0);
                pyUserNum.set('isRecommend', false);
                pyUserNum.set('countNum', 0);
                pyUserNum.save().then(function (results) {
                    if (!circleId) {
                        res.success("增加关注人数成功");
                    } else {
                        //如果圈子ID不为空,则还需要将圈子的数据更新
                        var pyCircle = new Parse.Object.extend("PYTopicCircle").createWithoutData(circleId);
                        var PYCircleUserNum = new Parse.Query("PYCircleUserNum");
                        PYCircleUserNum.equalTo('user', userObj);
                        PYCircleUserNum.equalTo('circle', pyCircle);
                        PYCircleUserNum.first().then(function (pyCircleUserNumObj) {
                            if (pyCircleUserNumObj) {
                                var oldCircleNumber = pyCircleUserNumObj.get('followerNum');
                                if (oldCircleNumber == 0 && parseInt(followType) == -1) {
                                    res.error("圈子关注数量已经为零,不能再取消关注");
                                    return;
                                }
                                pyCircleUserNumObj.increment('followerNum', parseInt(followType));
                                pyCircleUserNumObj.save().then(function (results) {
                                    res.success("增加关注人数成功,圈子数据同步修改");
                                }, function (err, error) {
                                    res.error("修改圈子数据失败");
                                })
                            } else {
                                var _PYCircleUserNum = Parse.Object.extend("PYCircleUserNum");
                                var _pyCircleUserNum = new _PYCircleUserNum();
                                _pyCircleUserNum.set('feedNum', 0);
                                _pyCircleUserNum.set('followerNum', 1);
                                _pyCircleUserNum.set('user', userObj);
                                _pyCircleUserNum.set('circle', pyCircle);
                                _pyCircleUserNum.set('isRecommend', false);
                                _pyCircleUserNum.set('askNum', 0);
                                _pyCircleUserNum.set('countNum', 0);
                                _pyCircleUserNum.save().then(function (results) {
                                    res.success("增加关注人数成功,增加圈子数据成功")
                                }, function (err, error) {
                                    res.error("增加圈子数据失败")
                                })
                            }
                        }, function (err, error) {
                            res.error("查询圈子记录失败");
                        })
                    }
                }, function (err, error) {
                    res.error("新增记录失败");
                })
            }
        }, function (err, error) {
            res.error("查询数据失败");
        })
    }, function (err, error) {
        res.error("获取用户对象失败");
    })

});

/**
 *
 */
Parse.Cloud.afterSave('PYQuestion', function (res, req) {
    var lastObj = res.object;
    var original = res.original;
    if (!original) {
        res.success("save不需要处理");
        return;
    }
    //若之前就有acceptAnswer则不作处理
    var acceptAnswer = original.get('acceptAnswer');
    if (acceptAnswer) {
        res.success("不做处理");
    } else {
        //表示本次操作采纳回答
        var coin = lastObj.get('coin');
        if (coin == 0) {
            res.success("0积分不需要加分减分")
        } else {
            //开始修改积分
            Parse.Cloud.useMasterKey();
            //根据answer获取回答认得ID
            var Answer = new Parse.Query("PYAnswer");
            var acceptedAns = lastObj.get("acceptAnswer");
            Answer.get(acceptedAns.id).then(function (answerObj) {
                var answerUser = answerObj.get("user");
                var _User = new Parse.Query("_User");
                _User.get(answerUser.id).then(function (opUser) {
                    //写入积分获得记录
                    FunctionAssert.addUserPoints(opUser, coin, "PYQuestion", 'answerAdopt', acceptedAns.id, opUser.get("point"), function (results) {
                        if (results) {
                            res.success("修改积分成功");
                        } else {
                            res.error("修改失败");
                        }
                    });
                });
            }, function (err, error) {
                res.error("修改积分失败");
            }, function (err, error) {
                res.error("获取答案详情失败");
            });
        }
    }
});

/**
 *
 */
Parse.Cloud.define("NearPharmacyList", function (req, res) {
    var location = req.params.location;
    var drugId = req.params.drugId;
    var page = req.params.page;

    if (!location) {
        res.error("请提供用户的经纬度坐标");
        return;
    }
    //获取高德地图周边药店数据
    FunctionAssert.getAmpAroundList(location, 1, function (resAMP) {
        if (!resAMP.pois.length) {
            res.error("获取到的药店数量为0");
            return;
        }
        //继续去寻找数据库中周边的认证药店
        var pharmacy = new Parse.Query("PYPharmacy");
        pharmacy.equalTo("status", "checked");
        var xL = location.split(',')[0];
        var yL = location.split(',')[1];
        var geoPoint = new Parse.GeoPoint({latitude: parseFloat(yL), longitude: parseFloat(xL)});
        pharmacy.withinKilometers('location', geoPoint, 3.0);

        pharmacy.find().then(function (pharmacies) {
            var pharmacyConfirmList = [];
            if (pharmacies.length == 0) {
                FunctionAssert.compareAMPAndLocal(pharmacyConfirmList, resAMP, res, function (resi, res1) {
                    res1.success(resi);
                    return;
                });
            }
            pharmacies.forEach(function (item) {
                var temp = {};
                temp.pharmacyId = item.id;
                temp.name = item.get('name');
                temp.address = item.get('address');
                temp.logo = item.get('logo') ? item.get('logo') : '';
                temp.location = item.get('location');
                temp.mapId = item.get('mapId');
                temp.tel = item.get('tel');
                temp.services = item.get('services');

                temp.distance = FunctionAssert.getFlatternDistance(yL, xL, temp.location.latitude, temp.location.longitude);
                temp.allowVip = item.get('allowVip') ? true : false;
                temp.showSale = item.get('showSale') ? true : false;
                temp.showRecommend = item.get("showRecommend") ? true : false;

                //寻找红包信息
                var CouponTemplate = new Parse.Query("PYCouponTemplate");
                CouponTemplate.containedIn('pharmacies', [item]);
                CouponTemplate.lessThan('validityBegin', new Date());
                CouponTemplate.greaterThan('validityEnd', new Date());
                CouponTemplate.descending('worth');
                CouponTemplate.ascending('created_at');

                CouponTemplate.first().then(function (coupon) {
                    if (!coupon) {
                        temp.hasCoupon = false;
                    } else {
                        temp.hasCoupon = coupon.get("isNoMore");
                    }

                    //寻找活动信息
                    var Activity = new Parse.Query("PYPharmacyActivity");
                    Activity.equalTo('pharmacy', item);
                    Activity.lessThan('beginDate', new Date());
                    Activity.greaterThan('endDate', new Date());
                    Activity.descending('isTop');
                    Activity.ascending('created_at');
                    Activity.first().then(function (activity) {
                        if (activity) {
                            temp.activityInfo = activity.get('name') + ',' + activity.get('content');
                        } else {
                            temp.activityInfo = '';
                        }
                        //寻找药品
                        //先获取所有的优惠药品的数量
                        Parse.Cloud.useMasterKey();
                        var pharmacyDrug = new Parse.Query("PYPharmacyDrug");
                        pharmacyDrug.equalTo('pharmacy', item);
                        pharmacyDrug.equalTo('isSale', true);
                        pharmacyDrug.count().then(function (count) {
                            if (count) {
                                temp.saleDrugCount = count;
                                //如果还有drug传入,则还要寻找是否有该药品正在优惠
                                if (drugId) {
                                    pharmacyDrug.equalTo('drug', Parse.Object.extend("PYDrug").createWithoutData(drugId));
                                    pharmacyDrug.first().then(function (drugInfo) {
                                        if (drugInfo) {
                                            temp.drugOnSale = true;
                                            temp.saleDrugInfo = {
                                                drugName: drugInfo.get("name"),
                                                drugHasSoldPrice: drugInfo.get("price") - drugInfo.get("salePrice")
                                            };
                                            pharmacyConfirmList.push(temp);
                                            if (pharmacyConfirmList.length == pharmacies.length) {
                                                FunctionAssert.compareAMPAndLocal(pharmacyConfirmList, resAMP, res, function (resi, res) {
                                                    res.success(resi);
                                                });
                                            }
                                        } else {
                                            //查看是否在售该药
                                            var _pharmacyDrug1 = new Parse.Query("PYPharmacyDrug");
                                            _pharmacyDrug1.equalTo('pharmacy', p);
                                            _pharmacyDrug1.equalTo('drug', Parse.Object.extend("PYDrug").createWithoutData(drugId));
                                            _pharmacyDrug1.first().then(function (drugSale) {
                                                temp.drugOnSale = drugSale ? true : false;
                                                pharmacyConfirmList.push(temp);
                                                if (pharmacyConfirmList.length == pharmacies.length) {
                                                    FunctionAssert.compareAMPAndLocal(pharmacyConfirmList, resAMP, res, function (resi, res1) {
                                                        res.success(resi);
                                                    });
                                                }
                                            });
                                        }
                                    })
                                } else {

                                    temp.drugOnSale = false;
                                    pharmacyConfirmList.push(temp);
                                    if (pharmacyConfirmList.length == pharmacies.length) {
                                        FunctionAssert.compareAMPAndLocal(pharmacyConfirmList, resAMP, res, function (resi, res1) {
                                            res1.success(resi);
                                        });
                                    }

                                }

                            } else {
                                temp.saleDrugCount = 0;
                                //查看是否在售该药
                                if (drugId) {
                                    var _pharmacyDrug2 = new Parse.Query("PYPharmacyDrug");
                                    _pharmacyDrug2.equalTo('pharmacy', item);
                                    _pharmacyDrug2.equalTo('drug', Parse.Object.extend("PYDrug").createWithoutData(drugId));
                                    _pharmacyDrug2.first().then(function (drugSale) {
                                        temp.drugOnSale = drugSale ? true : false;
                                        pharmacyConfirmList.push(temp);
                                        if (pharmacyConfirmList.length == pharmacies.length) {
                                            FunctionAssert.compareAMPAndLocal(pharmacyConfirmList, resAMP, res, function (resi, res1) {
                                                res1.success(resi);
                                            });
                                        }
                                    });
                                } else {
                                    pharmacyConfirmList.push(temp);
                                    if (pharmacyConfirmList.length == pharmacies.length) {
                                        FunctionAssert.compareAMPAndLocal(pharmacyConfirmList, resAMP, res, function (resi, res1) {
                                            res1.success(resi);
                                        });
                                    }
                                }
                            }
                        }, function (err) {
                            console.log('error:');
                        });
                    }, function (err) {
                        console.log(err);
                    });
                }, function (err) {
                    console.log(err);
                });

            });
        }, function (error) {
            console.log(error);
        });
    }, function (err, error) {
        console.log("获取失败");
    });
});

/**+
 * 处理推送逻辑,当在message中写入数据后执行推送
 */
Parse.Cloud.afterSave("PYNewMessage", function (req, res) {
    //获取数据信息
    var lastObj = req.object;
    if (req.original) {
        //表示本次操作是修改数据,不用推送处理
        res.success("修改无推送操作");
        return;
    }
    //获取服务器sever_url

    //然后检查消息类别,drugComment,feedComment,questionAnswer,channel,platform,all
    var messageType = lastObj.get("type");
    var fromUser = lastObj.get("fromUser");
    var toUser = lastObj.get("toUser");
    var targetId = lastObj.get("relatedId");
    switch (messageType) {
        case 'drugComment':
            FunctionAssert.sendPushToSingleUser(messageType, fromUser, toUser, targetId);
            break;
        case 'feedComment':
            FunctionAssert.sendPushToSingleUser(messageType, fromUser, toUser, targetId);
            break;
        case 'questionAnswer':
            FunctionAssert.sendPushToSingleUser(messageType, fromUser, toUser, targetId);
            break;
        case 'answerAdopt':
            FunctionAssert.sendPushToSingleUser(messageType, fromUser, toUser, targetId);
            break;
        case 'channel':
            FunctionAssert.sendPushToUsers(messageType, fromUser, toUser, targetId);
            break;
        case 'platform':
            FunctionAssert.sendPushToUsers(messageType, fromUser, toUser, targetId);
            break;
        case 'all':
            FunctionAssert.sendPushToUsers(messageType, fromUser, toUser, targetId);
            break;
        default :
            //无需推送,直接返回正确
            res.success("不需要推送的类型");
            break;
    }
});

/**
 *
 */
Parse.Cloud.define('unreadMessageMove', function (req, res) {

    var user = req.user;
    var messageType = req.params.messageType;
    var allMessage = {
        'system': ['system', 'couponGet', 'couponUse', 'VIPCard'],
        'comments': ['drug', 'feedComment', 'questionAnswer'],
        'likes': ['drugCommentLike', 'feedLike'],
        'follow': ['follow'],
        'chat': ['chat'],
        'answerAdopt': ['answerAdopt']
    };

    if (!messageType) {
        res.error("请指定对应的消息类别");
        return;
    }
    if (!user) {
        res.error("没有获取到对应的用户");
        return;
    }
    //寻找对应的用户对应的消息类别
    var PYMessage = new Parse.Query("PYNewMessage");
    PYMessage.equalTo('toUser', user);
    PYMessage.containedIn('type', allMessage[messageType]);
    PYMessage.equalTo('isRead', false);
    PYMessage.find().then(function (messages) {
        if (!messages) {
            res.error("获取未读消息为空");
            return;
        }
        if (messages.length > 0) {
            //表示寻找到了数据
            var promises = messages.map(function (message) {
                message.set("isRead", true);
                message.save();
            });
            res.success("修改完成");
            return Parse.default.Promise.when(promises);
        } else {
            res.success("没有修改数据");
        }
    }, function (err, error) {
        res.error("查询数据错误");
    });
});

/**
 * 根据手机号验证码快捷登陆
 * 此处处理逻辑,首先检查手机号码是否存在本系统
 * 1.如果存在,则发送验证码后无密码登陆
 * 2.如果不存在,需要新建立用户,然后有密码登陆
 *
 *
 */
Parse.Cloud.define('mobileFastLogin', function (req, res) {
    var mobile = req.params.mobile;
    var code = req.params.code;
    var comeFrom = req.params.comeFrom;
    if (!comeFrom) {
        comeFrom = 'hm_pinyao';
    }
    if (!mobile) {
        res.error("获取电话失败");
        return;
    }
    if (!code) {
        res.error("验证码不能为空");
        return;
    }
    //组装请求参数
    var data = {
        sms_code: code,
        code_type: 'mobileLogin',
        mobile: mobile
    };
    //先验证验证码是否正确
    Parse.Cloud.httpRequest({
        method: 'POST',
        body: data,
        headers: {
            'Content-Type': 'application/json;charset=utf-8',
            'X-Parse-Application-Id': 'myAppId',
            'X-Parse-Master-Key': 'masterKey'
        },
        url: 'http://127.0.0.1:1337/parse/functions/validateSMSCode'
    }).then(function (httpResponse) {
        //验证码验证成功,根据手机号查询用户:
        var _User = new Parse.Query("_User");
        _User.equalTo('mobile', mobile);
        _User.first().then(function (userObj) {
            if (userObj) {
                //存在用户,则要开启无密码登陆
                Parse.Cloud.httpRequest({
                    method: 'get',
                    body: {mobile: mobile},
                    headers: {
                        'Content-Type': 'application/json;charset=utf-8',
                        'X-Parse-Application-Id': 'myAppId',
                        'X-Parse-Master-Key': 'masterKey'
                    },
                    url: 'http://127.0.0.1:1337/parse/mobileLogin'
                }).then(function (httpLoginResponse) {
                    var vResLogin = JSON.parse(httpLoginResponse.text);
                    res.success(vResLogin);
                }, function (error, err) {
                    console.log(error.text, err);
                    res.error("登陆失败");
                })
            } else {
                //表示该手机用户不存在,则启用注册逻辑
                var password = FunctionAssert.getPassCode(6);
                console.log(password);
                Parse.Cloud.httpRequest({
                    method: 'post',
                    body: {
                        username: mobile,
                        password: password,
                        mobile: mobile,
                        signFrom: comeFrom,
                        sex: "",
                        avatar:"AppIcon512.png",
                        userType:"normal",
                        nickname:mobile,
                        birthday:"",
                        age:"",
                        point:0
                    },
                    headers: {
                        'Content-Type': 'application/json;charset=utf-8',
                        'X-Parse-Application-Id': 'myAppId',
                        'X-Parse-Master-Key': 'masterKey'
                    },
                    url: 'http://127.0.0.1:1337/parse/users'
                }).then(function (httpLoginResponse) {
                    var vResLogin = JSON.parse(httpLoginResponse.text);
                    if (vResLogin.error) {
                        res.error("注册失败");
                    } else {
                        //登陆成功则获取到用户信息
                        res.success(vResLogin);
                        //后续需要将密码短信发送到用户
                        Parse.Cloud.httpRequest({
                            method: 'post',
                            body: {mobile: mobile, send_type: 'mobileAutoSign', password: password},
                            headers: {
                                'Content-Type': 'application/json;charset=utf-8',
                                'X-Parse-Application-Id': 'myAppId',
                                'X-Parse-Master-Key': 'masterKey'
                            },
                            url: 'http://127.0.0.1:1337/parse/functions/sendSMS'
                        }).then(function (response) {});
                        //此处需要添加积分
                        var signedUser = new Parse.User();
                        signedUser.id = vResLogin.objectId;
                        FunctionAssert.addUserPoints(signedUser, 100, "user", 'FirstMobileSign', vResLogin.objectId, 0, function (res) {});
                    }
                }, function (error, err) {
                    console.log(error.text, err);
                })
            }
        }, function (error, err) {
            res.error("查询失败");
        })

    }, function (httpResponse) {
        res.error(JSON.parse(httpResponse.text).error);
    });

});

Parse.Cloud.define('createdRandomCoupons', function (req, res) {
    var key = req.params.keyOp;
    if (key != 'xiaojun') {
        res.error("非法操作");
        return;
    }
    //获取template对象
    var query = new Parse.Query("PYCouponTemplate");
    query.get('efbMs1LVjt').then(function (T) {
        if (T) {
            for (var i = 0; i < 10; i++) {
                var Coupon = Parse.Object.extend('PYCoupon');
                var coupon = new Coupon();
                coupon.set('couponTemplate', T);
                coupon.set('redeemCode', (new Date().getTime().toString().substr(3, 6)) + FunctionAssert.MathRand());
                coupon.save();
            }
        }
        res.success("创建成功了");
    });
});

Parse.Cloud.define('getUserOpenId', function (req, res) {
    var userId = req.params.userId;
    var user = new Parse.Query('_User');
    user.get(userId).then(function (userObj) {
        var openId = userObj.get('wxOpenId');
        if (openId) {
            res.success(openId);
        } else {
            res.error("获取失败");
        }
    }, function (err) {
        res.error("获取失败");
    })
});

Parse.Cloud.define('setUserOpenId', function (req, res) {
    var userId = req.params.userId;
    var openId = req.params.openId;
    var user = new Parse.Query('_User');
    user.get(userId, function (userObj) {
        if (userObj) {
            userObj.set('wxOpenId', openId);
            userObj.save().then(function (results) {
                res.success("写入成功");
            }, function (error) {
                res.error("写入失败");
            })
        }
    })
});


Parse.Cloud.define('changeMemberType', function (req, res) {
    var userId = req.params.userId;
    var userType = req.params.userType;
    var query = new Parse.Query('User');
    Parse.Cloud.useMasterKey();
    query.get(userId).then(function (user) {
        console.log(user.get('userType'));
        user.set('userType', userType);
        return user.save();
    }, function (error) {
        console.log(error.message);
        res.error('修改失败');
    }).then(function (result) {
        res.success("修改成功");
    }, function (error) {
        console.log(error.message);
        res.error('修改失败');
    });
});

Parse.Cloud.define('addUserPoints', function (req,res) {
    var userId = req.params.userId;
    var addType = req.params.addType;
    var number = req.params.number;
    if(!userId || !addType || !number){
        res.error("获取添加信息失败");
    }
    var user = new Parse.Query('_User');
    user.get(userId).then(function(addUser){
        //先获取用户的旧积分数
        var oldPoints = addUser.get('point');
        Parse.Cloud.useMasterKey();
        if(!oldPoints){
            //没有发现point字段,则直接save
            addUser.set('point',0);
            addUser.save().then(function (user) {
                FunctionAssert.addUserPoints(user,number,'user',addType,userId,0,function(resAdd){
                    if(resAdd){
                        res.success("添加成功");
                    }else{
                        res.error("添加失败");
                    }
                })
            });
            return;
        }
        FunctionAssert.addUserPoints(addUser,number,'user',addType,userId,oldPoints,function(resAdd){
            if(resAdd){
                res.success("添加成功");
            }else{
                res.error("添加失败");
            }
        })
    },function(err){
        res.error("获取用户失败");
    });
});
// 最近5天的交易记录
Parse.Cloud.define('getLastFiveDayTradeLog', function (req, res) {
    var storeId = req.params.storeId;
    if (assert.check_parms([storeId])){
        res.error(assert.con2json(101, '店铺ID不能为空'));
        return;
    }
    co(function* () {
        // 先查询前4天的记录
        var Store = Parse.Object.extend('OPStore');
        var store = new Store();
        store.id = storeId;
        var tradeLogs = yield new Promise(function (resolve, reject) {
            // var today = new Date();
            // today.setHours(0, 0, 0, 0);
            // var fiveDaysAgo = new Date(today);
            // fiveDaysAgo.setDate(today.getDate() - 4);
            // fiveDaysAgo.setHours(0, 0, 0, 0);
            var query = new Parse.Query('KDTradeLog');
            query.equalTo('store', store);
            // query.greaterThan('createdAt', fiveDaysAgo);
            // query.lessThan('createdAt', today);
            query.limit(4);
            query.select('orderCount', 'income', 'tourist');
            query.descending('createdAt');
            query.find().then(function (res) {
                resolve(res);
            }, function (error) {
                reject(error)
            });
        });
        // 获取今日的交易记录
        var todayLogs = yield new Promise(function (resolve, reject) {
            var today = new Date();
            today.setHours(0, 0, 0, 0);
            var query = new Parse.Query('OPOrder');
            query.greaterThan('createdAt', today);
            query.equalTo('store', store);
            query.containedIn('status', [1,2,3,4]);
            query.select('cost', 'payPrice');
            query.find().then(function (results) {
                resolve(results)
            }, function (error) {
                reject(error)
            });
        });
        var response_content = {
            income: [],
            orderCount: [],
            tourist: []
        };
        // 倒转下过去4天的交易记录，为了显示的时候是正序
        tradeLogs.reverse();
        // 将记录插入到对应的对象里，income/orderCount/tourist
        tradeLogs.forEach(function (item) {
            // 统计内容先一天的内容，要对输出的日期做调整
            var stat_date = item.get('createdAt');
            stat_date.setDate(stat_date.getDate()-1);
            var date = stat_date.getDate();
            var income_temp = {};
            var orderCount_temp = {};
            var tourist_temp = {};
            income_temp[date] = item.get('income');
            orderCount_temp[date] = item.get('orderCount');
            tourist_temp[date] = item.get('tourist');
            response_content.income.push(income_temp);
            response_content.orderCount.push(orderCount_temp);
            response_content.tourist.push(tourist_temp);
        });
        // 整理今日的数据，从redis里取出今日的浏览人数
        var income_temp = 0;
        var orderCount_temp = 0;
        todayLogs.forEach(function (item) {
            orderCount_temp += 1;
            income_temp += item.get('payPrice') - item.get('cost');
        });
        // 获取到今日的浏览量，插入到返回值中
        var client = assert.getRedis();
        client.get(storeId, function (err, reply) {
            if (err){
                res.error(assert.con2json(400, '获取失败'));
                return;
            }
            var tourist = 0;
            if (typeof reply == 'string' && reply != "NaN"){
                tourist = parseInt(reply);
            }
            var today_date = new Date().getDate();
            var temp_income = {};
            var temp_orderCount = {};
            var temp_tourist = {};
            temp_income[today_date] = income_temp;
            temp_orderCount[today_date] = orderCount_temp;
            temp_tourist[today_date] = tourist;
            response_content.income.push(temp_income);
            response_content.orderCount.push(temp_orderCount);
            response_content.tourist.push(temp_tourist);
            // 检查是否够5天的数据
            var returnLen = response_content.income.length;
            if (returnLen<5){
                var limit = 5-returnLen;
                for (var i=0; i<limit; i++){
                    var temp_date = new Date();
                    var set_date = new Date(temp_date);
                    set_date.setDate(temp_date.getDate()-returnLen-i);
                    temp_date = set_date.getDate();
                    var temp = {};
                    temp[temp_date] = 0;
                    response_content.income.unshift(temp);
                    response_content.orderCount.unshift(temp);
                    response_content.tourist.unshift(temp);
                }
            }
            res.success(assert.con2json(200, 'success', response_content));
        });
    });
});
// 获取今日订单，今日访客，今日数据
Parse.Cloud.define('todayTradeDetail', function (req, res) {
    var storeId = req.params.storeId;
    if (assert.check_parms([storeId])){
        res.error(assert.con2json(101, '店铺ID不能为空'));
        return;
    }
    co(function* () {
        var client = assert.getRedis();
        // 获取今日的交易记录
        var todayLogs = yield new Promise(function (resolve, reject) {
            var today = new Date();
            today.setHours(0, 0, 0, 0);
            var Store = Parse.Object.extend('OPStore');
            var store = new Store();
            store.id = storeId;
            var query = new Parse.Query('OPOrder');
            query.equalTo('store', store);
            query.greaterThan('createdAt', today);
            query.containedIn('status', [1,2,3,4]);
            query.select('cost', 'payPrice');
            query.find().then(function (results) {
                resolve(results)
            }, function (error) {
                reject(error)
            });
        });
        // 整理今日的数据，从redis里取出今日的浏览人数
        var income_temp = 0;
        var orderCount_temp = 0;
        todayLogs.forEach(function (item) {
            orderCount_temp += 1;
            income_temp += item.get('payPrice') - item.get('cost');
        });
        var response_content = {
            income: income_temp,
            orderCount: orderCount_temp,
            tourist: 0
        };
        // 将记录插入到对应的对象里，income/orderCount/tourist
        client.get(storeId, function (err, reply) {
            if (err){
                res.error(assert.con2json(400, '获取失败'));
            }
            var tourist = 0;
            if (typeof reply == 'string' && reply != "NaN"){
                tourist = parseInt(reply);
            }
            response_content.tourist = tourist;
            res.success(assert.con2json(200, 'success', response_content));
        });
    });

});
// 获取店铺本月的客户浏览统计
Parse.Cloud.define('monthTouristLog', function (req, res) {
    var storeId = req.params.storeId;
    var page = req.params.page;
    var totalTourist = 0;
    if (assert.check_parms([storeId])){
        res.error(assert.con2json(101, '店铺ID不能为空'));
        return;
    }
    try {
        page = parseInt(page);
        page = page <1 ? 0: page
    }catch (error){
        page =1;
    }
    co(function* () {
        var Store = Parse.Object.extend('OPStore');
        var store = new Store();
        store.id = storeId;
        try {
            var browseLogs = yield new Promise(function (resolve, reject) {
                var query = new Parse.Query('KDUserBrowse');
                var now = new Date();
                var first = new Date(now);
                first.setDate(1);
                query.include('user');
                query.equalTo('store',store);
                query.ascending('browseDateTime');
                query.greaterThan('browseDateTime', first);
                query.find().then(function (results) {
                    resolve(results)
                }, function (error) {
                    reject(error)
                });
            });
        }catch (error){
            res.success(assert.con2json(400, 'fail'))
        }
        var userList = [];
        var returnContent = [];
        var temp={};
        Array.prototype.contains = function(element){
            return this.indexOf(element) > -1;
        };
        browseLogs.forEach(function (item) {
            var user = item.get('user');
            try {
                var userId = user.id
            }catch (error){
                return;
            }
            if (!userList.contains(userId)){
                userList.push(userId);
                temp[userId] = {count:0, lastBrowse: null};
                temp[userId].userId = userId;
                temp[userId].name = user.get('nickname');
                temp[userId].avatar = assert.checkAvatar(user.get('avatar'));
            }
            temp[userId].count += 1;
            temp[userId].lastBrowse = item.get('browseDateTime').getTime();
        });
        for (var key in temp){
            totalTourist += 1;
            returnContent.push(temp[key]);
        }
        // if (returnContent.length>10){
            var sliced = returnContent.slice((page-1)*10,10);
        // }
        if (sliced.length<1){
            res.success(assert.con2json(200, '没有更多记录了',{count: totalTourist, touristLog: []}));

        }else {
            res.success(assert.con2json(200, '获取用户浏览记录成功', {count: totalTourist, touristLog: sliced}));
        }
    });
});
// 统计kd微店每日的交易记录
Parse.Cloud.job("dailyTradeLog", function(request, status) {
    co(function* () {
        var count = yield checkJob("dailyTradeLog");
        if (count){
            status.success("已经执行过了");
            return
        }
        // 获取所有的店铺
        try {
            var stores = yield new Promise(function (resolve, reject) {
                var query = new Parse.Query('OPStore');
                query.select('id');
                query.find().then(function (res) {
                    resolve(res);
                }, function (error) {
                    reject(error)
                });
            });
        }catch (error){
            status.error(error.message)
        }
        // 获取过去一天的所有订单
        try {
            var today = new Date();
            today.setHours(0, 0, 0, 0);
            var yesterday = new Date(today);
            yesterday.setDate(today.getDate() - 1);
            yesterday.setHours(0, 0, 0, 0);
            var orders = yield new Promise(function (resolve, reject) {
                var query = new Parse.Query('OPOrder');
                query.greaterThan('payDate', yesterday);
                query.lessThan('payDate', today);
                query.containedIn('status', [1,2,3,4]);
                query.select('payPrice', 'store', 'user', 'cost');
                query.find().then(function (res) {
                    resolve(res);
                }, function (error) {
                    reject(error)
                });
            });
        }catch (error){
            status.error(error.message)
        }
        var store_list = [];
        var store_info = {};
        // 为每一个店铺创建一个店铺info

        stores.forEach(function (item) {
            var store = item.id;
            store_info[store] = {'turnover':0, 'orderCount':0, 'income':0, 'tourist': 0, 'userCount': 0};
            store_list.push(store);
        });
        // 遍历说有订单，计算店铺的info
        orders.forEach(function (item) {
            var storeId = item.get('store').id;
            var store = store_info[storeId];
            store.turnover += item.get('payPrice');
            store.orderCount += 1;
            store.income += item.get('payPrice') - item.get('cost');
        });
        // 将店铺的info插入到数据库
        var wait = [];
        // 计算昨天的日期
        var date = new Date();
        date.setDate(date.getDate()-1);
        var day = date.getDate();
        day = getFormattedPartTime(day);
        var month = date.getMonth() + 1;
        month = getFormattedPartTime(month);
        var year = date.getYear().toString();
        year = year.slice(-2);
        day = parseInt(year+month+day);
        for (var item in store_info){
            var Store = Parse.Object.extend('OPStore');
            var store = new Store();
            store.id = item;
            var TradeLog = Parse.Object.extend('KDTradeLog');
            var tradeLog = new TradeLog();
            tradeLog.set('turnover', store_info[item].turnover);
            tradeLog.set('orderCount', store_info[item].orderCount);
            tradeLog.set('income', store_info[item].income);
            tradeLog.set('turnover', store_info[item].turnover);
            tradeLog.set('tourist', store_info[item].tourist);
            tradeLog.set('userCount', store_info[item].userCount);
            tradeLog.set('store', store);
            tradeLog.set('day', day);
            wait.push(tradeLog.save())
        }
        // 将店铺总访问数量插入到数据
        var taskList = [];
        Promise.all(wait).then(function (results) {
            results.forEach(function (item) {
                var storeId = item.get('store').id;
                var client = assert.getRedis();
                client.on("error", function (err) {
                    console.log("Error " + err);
                });
                client.get(storeId, function (err, reply) {
                    if (err){
                        console.log('tourist inject fail');
                        status.error(err.message)
                    }else {
                        if (typeof reply == 'string' && reply != 'NaN'){
                            var tourist = parseInt(reply);
                            item.set('tourist', tourist);
                            taskList.push(item.save());
                        }
                    }
                });
                // 获取到这个店铺的所有浏览信息，保存到数据库
                client.hgetall(storeId.split("").reverse().join(""), function (err, obj) {
                    if (err){
                        status.error(err.message)
                        console.log('tourist inject fail');
                    }else {
                        if (obj){
                            var userCount = Object.keys(obj).length;
                            item.set('userCount', userCount);
                            taskList.push(item.save());
                        }
                    }
                });
            });
        }, function (error) {
            status.error("dailyTradeLog There was an error"+error.message);
        });
        Promise.all(taskList).then(function (data) {
            status.success('dailyTradeLog success');
            insertJobLog("dailyTradeLog", "success");
        }, function (error) {
            status.error('dailyTradeLog error'+error.message);
            insertJobLog("dailyTradeLog", "fail");
        });
    });

});
// kd微店月交易记录统计
Parse.Cloud.job("monthTradeLog", function (request, status) {
    co(function* () {
        var count = yield checkJob("monthTradeLog");
        if (count){
            status.success("已经执行过了");
            return
        }
        // 先获取所有店铺本月的月销售记录，判断是否已经初始化过了
        var date = new Date();
        var yesterday = new Date(date);
        yesterday.setHours(0,0,0,0);
        date.setDate(date.getDate()-1);
        var month = date.getMonth() + 1;
        var year = date.getYear().toString();
        year = year.slice(-2);
        month = getFormattedPartTime(month);
        month = parseInt(year+month);
        // 获取当天每个店铺的天交易记录，然后加入到月交易里
        try {
            var tradeLogs = yield new Promise(function (resolve, reject) {
                var query = new Parse.Query('KDTradeLog');
                query.greaterThan('createdAt', yesterday);
                query.find().then(function (results) {
                    resolve(results);
                }, function (error) {
                    reject(error);
                });
            });
        }catch (error){
            status.error(error.message)
        }
        // 将所有的店铺统计按照店铺ip归类
        var stores_info = {};
        tradeLogs.forEach(function (item) {
            var storeId = item.get('store').id;
            stores_info[storeId] = {};
            stores_info[storeId].turnover = item.get('turnover');
            stores_info[storeId].orderCount = item.get('orderCount');
            stores_info[storeId].income = item.get('income');
            stores_info[storeId].tourist = item.get('tourist');
            stores_info[storeId].userCount = item.get('userCount');
            stores_info[storeId].month = month;
        });

        // 获取这个店铺本月的统计记录
        try {
            var monthLogs = yield new Promise(function (resolve, reject) {
                var query = new Parse.Query('KDTradeMonthLog');
                query.equalTo('month', month);
                query.find().then(function (res) {
                    resolve(res);
                }, function (error) {
                    reject(error)
                });
            });
        }catch (error){
            status.error(error.message);
        }
        var isFirstDay = monthLogs.length == 0;
        var Store = Parse.Object.extend('OPStore');
        var TradeMonthLog = new Parse.Object.extend('KDTradeMonthLog');
        var store = null;
        var tradeMonthLog = null;
        var taskList = [];
        if (isFirstDay){
            // 保存每个店铺的总信息
            for (var key in stores_info){
                store = new Store();
                store.id = key;
                stores_info[key].store = store;
                tradeMonthLog = new TradeMonthLog();
                taskList.push(tradeMonthLog.save(stores_info[key]));
            }
        }else {
            // 先判断这次有没有新的店铺添加进来，如果有就为新添加的店铺init
            var storeId_list = [];
            monthLogs.forEach(function (item) {
                store = item.get('store');
                storeId_list.push(item.get('store').id)
            });
            Array.prototype.contains = function(element){
                return this.indexOf(element) > -1;
            };
            for (var storeID in stores_info){
                if (!storeId_list.contains(storeID)){
                    store = new Store();
                    store.id = storeID;
                    stores_info[storeID].store = store;
                    tradeMonthLog = new TradeMonthLog();
                    taskList.push(tradeMonthLog.save(stores_info[storeID]));
                }
            }
            monthLogs.forEach(function (item) {
                var storeId = item.get('store').id;
                var storeInfo = stores_info[storeId];
                if (typeof storeInfo == 'undefined'){
                    return
                }
                if (item.get("updatedAt")>yesterday){
                    return
                }
                item.increment('turnover', storeInfo.turnover);
                item.increment('orderCount', storeInfo.orderCount);
                item.increment('income', storeInfo.income);
                item.increment('tourist', storeInfo.tourist);
                item.increment('userCount', storeInfo.userCount);
                taskList.push(item.save());
            });
        }
        Promise.all(taskList).then(function (data) {
            status.success('monthTradeLog success');
            insertJobLog("monthTradeLog", "success");
        }, function (error) {
            status.error('monthTradeLog error'+error.message);
            insertJobLog("monthTradeLog", "fail");
        });
    });
});
// 将登陆用户的浏览记录写到数据控中
Parse.Cloud.job("browseLogToDB", function (request, status) {
    co(function* () {
        var count = yield checkJob("browseLogToDB");
        if (count){
            status.success("已经执行过了");
            return
        }
        // 获取所有的店铺
        try {
            var stores = yield new Promise(function (resolve, reject) {
                var query = new Parse.Query('OPStore');
                query.select('id');
                query.find().then(function (res) {
                    resolve(res);
                }, function (error) {
                    reject(error);
                });
            });
        }catch (error){
            status.error(error.message);
        }
        // 获取redis客户端
        var client = assert.getRedis();
        // 将每个店铺的浏览记录查出来，然后插入
        var taskList = [];
        stores.forEach(function (item) {
            var Store = Parse.Object.extend('OPStore');
            var store = new Store();
            store.id = item.id;

            var user = new Parse.User();
            // 获取到这个店铺的所有浏览信息，保存到数据库

            client.hgetall(item.id.split("").reverse().join(""), function (err, obj) {
                var UserBrowse = Parse.Object.extend('KDUserBrowse');
                for (var key in obj){
                    var userBrowse = new UserBrowse();
                    user.id = obj[key];
                    userBrowse.set('user', user);
                    userBrowse.set('store', store);
                    userBrowse.set('browseDateTime', new Date(key));
                    taskList.push(userBrowse.save());
                }
            });

        });
        Promise.all(taskList).then(function (data) {
            status.success('browseLogToDB success');
            insertJobLog("browseLogToDB", "success");
        }, function (error) {
            status.error('browseLogToDB error'+error.message);
            insertJobLog("browseLogToDB", "fail");
        });
    });
});
// 计算团队贡献
Parse.Cloud.job("calculateTeamReward", function (request, status) {
    var limit = 100;
    var money = 5;
    co(function* () {
        var count = yield checkJob("calculateTeamReward");
        if (count){
            status.success("已经执行过了");
            return
        }
        // 获取所有的店铺
        try {
            var stores = yield new Promise(function (resolve, reject) {
                var query = new Parse.Query('OPStore');
                query.select('totalCost');
                query.find().then(function (res) {
                    resolve(res);
                }, function (error) {
                    reject(error)
                });
            });
        }catch (error){
            status.error(error.message);
        }
        try {
            var rewardLogs = yield new Promise(function (resolve, reject) {
                var query = new Parse.Query('OPTeamReward');
                query.equalTo('limit', limit);
                query.find().then(function (res) {
                    resolve(res);
                }, function (error) {
                    reject(error)
                });
            });
        }catch (error){
            status.error(error.message);
        }
        Array.prototype.contains = function(element){
            return this.indexOf(element) > -1;
        };
        var rewardLogList = [];
        rewardLogs.forEach(function (item) {
            rewardLogList.push(item.get('store').id);
        });
        // 计算每个店铺的totalCost
        var taskList = [];
        stores.forEach(function (item) {
            if (rewardLogList.contains(item.id)){
                return
            }
            var totalCost = item.get('totalCost');
            if (totalCost == 'undefined'){
                console.log(item.id);
                return;
            }
            if (totalCost>limit){
                var TeamReward = Parse.Object.extend('OPTeamReward');
                var teamReward = new TeamReward();
                teamReward.set('store', item);
                teamReward.set('limit', limit);
                teamReward.set('money', money);
                taskList.push(teamReward.save());
            }
        });
        Promise.all(taskList).then(function (data) {
            status.success('calculateTeamReward success');
            insertJobLog("calculateTeamReward", "success");
        }, function (error) {
            status.error('calculateTeamReward error'+error.message);
            insertJobLog("calculateTeamReward", "fail");

        });
    });
});
// 自动确认收货，取消长时间未付款的订单
Parse.Cloud.job("checkOrder", function (request, status) {
    co(function* () {
        var count = yield checkJob("checkOrder");
        if (count){
            status.success("已经执行过了");
            return
        }
        try{
            var notPayOrders = yield new Promise(function (resolve, reject) {
                var query = new Parse.Query("OPOrder");
                query.equalTo("status", 0);
                query.include('orderProducts');
                query.find().then(function (res) {
                    resolve(res);
                }, function (error) {
                    reject(error);
                });
            });
        }catch (error){
            status.error(error.message);
        }
        var wait = [];
        notPayOrders.forEach(function (item) {
            var now = new Date();
            var oneDayBefore = new Date(now);
            oneDayBefore.setDate(now.getDate()-1);
            if (item.get("createdAt")<oneDayBefore){
                var orderProducts = item.get('orderProducts');
                orderProducts.forEach(function (orderProduct) {
                    wait.push(orderProduct.destroy());
                });
                wait.push(item.destroy());
            }
        });
        Promise.all(wait).then(function (results) {
            console.log(results);
            status.success("delete unPayment orders");
            insertJobLog("checkOrder", "success");
        }, function (error) {
            status.error(error.message);
            insertJobLog("checkOrder", "fail");
        });
    });
    
});
// 自动确认收货，取消长时间未付款的订单
Parse.Cloud.job("autoConfirm", function (request, status) {
    co(function* () {
        var count = yield checkJob("autoConfirm");
        if (count){
            status.success("已经执行过了");
            return
        }
        try{
            var now = new Date();
            var sevenDaysBefore = new Date(now);
            sevenDaysBefore.setDate(now.getDate()-7);
            var notConfirmedOrders = yield new Promise(function (resolve, reject) {
                var query = new Parse.Query("OPOrder");
                query.equalTo("status", 2);
                query.lessThan("updatedAt", sevenDaysBefore);
                query.find().then(function (res) {
                    resolve(res);
                }, function (error) {
                    reject(error);
                });
            });
        }catch (error){
            status.error(error.message);
        }
        var wait = [];
        notConfirmedOrders.forEach(function (item) {
            item.set("status", 3);
            wait.push(item.save());
        });
        Promise.all(wait).then(function (results) {
            status.success("autoConfirm orders success");
            insertJobLog("autoConfirm", "success");

        }, function (error) {
            status.error("autoConfirm orders fail"+error.message);
            insertJobLog("autoConfirm", "fail");
        });
    });
});
// 格式化月日 1日to 01日 1月改为01月
function getFormattedPartTime(partTime){
    if (partTime<10)
        return "0"+partTime;
    return partTime.toString();
}
function insertJobLog(jobName, status) {
    var date = new Date();
    var day = date.getDate();
    day = getFormattedPartTime(day);
    var month = date.getMonth() + 1;
    month = getFormattedPartTime(month);
    var year = date.getYear().toString();
    year = year.slice(-2);
    day = parseInt(year+month+day);
    var JobLog = Parse.Object.extend("KDJobs");
    var jobLog = new JobLog();
    jobLog.set("day", day);
    jobLog.set("jobName", jobName);
    jobLog.set("status", status);
    jobLog.save().then(function (res) {
        console.log("insert log success");
    }, function (error) {
        console.log("insert log fail");
    });
}
function checkJob(jobName) {
    var date = new Date();
    var day = date.getDate();
    day = getFormattedPartTime(day);
    var month = date.getMonth() + 1;
    month = getFormattedPartTime(month);
    var year = date.getYear().toString();
    year = year.slice(-2);
    day = parseInt(year+month+day);
    return new Promise(function (resolve, reject) {
        var query = new Parse.Query("KDJobs");
        query.equalTo("day", day);
        query.equalTo("jobName", jobName);
        query.count().then(function (count) {
            resolve(count);
        }, function (error) {
            reject(error);
        })
    });
}